<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['wms:order:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['wms:order:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['wms:order:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
                   v-hasPermi="['wms:order:export']">
          导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="库单ID" align="center" prop="id"/>
      <el-table-column label="单据类型" align="center" prop="orderTypeId"/>
      <el-table-column label="发货方" align="center" prop="deliveryId"/>
      <el-table-column label="收货方" align="center" prop="receiveId"/>
      <el-table-column label="单据状态" align="center" prop="state"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wms:order:edit']">
            单据修改
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleOrderLineUpdate(scope.row)"
                     v-hasPermi="['wms:order:edit']">
            单据明细修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['wms:order:remove']">
            删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="单据来源" align="center" prop="sourceId"/>
      <el-table-column label="生产厂商" align="center" prop="manufacturerId"/>
      <el-table-column label="申请人" align="center" prop="userApplicantId"/>
      <el-table-column label="审核人" align="center" prop="userAuditorId"/>
      <el-table-column label="发货员" align="center" prop="userDeliveryId"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="创建者" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新者" align="center" prop="updateBy"/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改跟物品有关的订单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="申请人" prop="userApplicantId">
          <el-input v-model="form.userApplicantId" placeholder="请输入申请人"/>
        </el-form-item>
        <el-form-item label="审核人" prop="userAuditorId">
          <el-input v-model="form.userAuditorId" placeholder="请输入审核人"/>
        </el-form-item>
        <el-form-item label="发货员" prop="userDeliveryId">
          <el-input v-model="form.userDeliveryId" placeholder="请输入发货员"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="租户" prop="tenantId">
          <el-input v-model="form.tenantId" placeholder="请输入租户"/>
        </el-form-item>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-form>
    </el-dialog>

    <!-- 添加或修改跟物品有关的订单对话框 -->
    <el-dialog :title="orderLine.title" v-model="orderLine.open" width="800px" append-to-body>
      <el-divider content-position="center">物品订单明细信息</el-divider>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="Plus" @click="handleAddWmsOrderLine">添加</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="Check" @click="">保存</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="Delete" @click="handleDeleteWmsOrderLine">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" icon="Close" @click="orderLine.open = false">关闭</el-button>
        </el-col>
      </el-row>
      <el-table :data="orderLine.list" :row-class-name="rowWmsOrderLineIndex"
                @selection-change="handleWmsOrderLineSelectionChange" ref="wmsOrderLine">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="序号" align="center" prop="index" width="50"/>
        <el-table-column label="单位" prop="measureUnit" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.measureUnit" placeholder="请输入单位"/>
          </template>
        </el-table-column>
        <el-table-column label="入库数量" prop="quantity" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.quantity" placeholder="请输入入库数量"/>
          </template>
        </el-table-column>
        <el-table-column label="库位ID" prop="areaId" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.areaId" placeholder="请输入库位ID"/>
          </template>
        </el-table-column>
        <el-table-column label="有效期" prop="expireDate" width="240">
          <template #default="scope">
            <el-date-picker clearable v-model="scope.row.expireDate"
                            type="date" value-format="YYYY-MM-DD" placeholder="请选择有效期">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="创建者" prop="createBy" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.createBy" placeholder="请输入创建者"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="240">
          <template #default="scope">
            <el-date-picker clearable v-model="scope.row.createTime"
                            type="date" value-format="YYYY-MM-DD" placeholder="请选择创建时间">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="更新者" prop="updateBy" width="150">
          <template #default="scope">
            <el-input v-model="scope.row.updateBy" placeholder="请输入更新者"/>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updateTime" width="240">
          <template #default="scope">
            <el-date-picker clearable v-model="scope.row.updateTime"
                            type="date" value-format="YYYY-MM-DD"
                            placeholder="请选择更新时间">
            </el-date-picker>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import {getorderLine, listOrder, getOrder, delOrder, addOrder, updateOrder} from "@/api/wms/order";

const {proxy} = getCurrentInstance();

const orderList = ref([]);
const wmsOrderLineList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedWmsOrderLine = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deliveryId: null,
    receiveId: null,
    state: null,
    sourceId: null,
  },
  rules: {}
});

/*** 订单明细参数 */
const orderLine = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "订单明细",
  //表格数据
  list: []
});

/*** 订单明细参数 */
const orderType = reactive({
  //
  id: null,
  // 弹出层标题
  name: null
});

function handleOrderLineUpdate(row) {
  orderLine.open = true;
  orderLine.title = "单据号：" + row.id;
}

const {queryParams, form, rules} = toRefs(data);

/** 查询跟物品有关的订单列表 */
function getList() {
  loading.value = true;
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderTypeId: null,
    deliveryId: null,
    receiveId: null,
    state: null,
    sourceId: null,
    manufacturerId: null,
    userApplicantId: null,
    userAuditorId: null,
    userDeliveryId: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  wmsOrderLineList.value = [];
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加跟物品有关的订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;
    wmsOrderLineList.value = response.data.wmsOrderLineList;
    open.value = true;
    title.value = "修改跟物品有关的订单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      form.value.wmsOrderLineList = wmsOrderLineList.value;
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除跟物品有关的订单编号为"' + _ids + '"的数据项？').then(function () {
    return delOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 物品订单明细序号 */
function rowWmsOrderLineIndex({row, rowIndex}) {
  row.index = rowIndex + 1;
}

/** 物品订单明细添加按钮操作 */
function handleAddWmsOrderLine() {
  let obj = {};
  obj.measureUnit = "";
  obj.quantity = "";
  obj.areaId = "";
  obj.expireDate = "";
  obj.remark = "";
  obj.createBy = "";
  obj.createTime = "";
  obj.updateBy = "";
  obj.updateTime = "";
  obj.tenantId = "";
  orderLine.list.push(obj);
}

/** 物品订单明细删除按钮操作 */
function handleDeleteWmsOrderLine() {
  if (checkedWmsOrderLine.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的物品订单明细数据");
  } else {
    const wmsOrderLines = wmsOrderLineList.value;
    const checkedWmsOrderLines = checkedWmsOrderLine.value;
    wmsOrderLineList.value = wmsOrderLines.filter(function (item) {
      return checkedWmsOrderLines.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleWmsOrderLineSelectionChange(selection) {
  checkedWmsOrderLine.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('wms/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

getList();
</script>
